# encoding=utf-8
import jieba
import jieba.analyse
import numpy as np
import re
import jieba.posseg
from pyhanlp import *
import json
import os
from docx import Document


def getFilePaths():
    path = 'temp'
    filelist = os.listdir(path)
    newlist = []
    for fileName in filelist:
        newlist.append(path + '/' + fileName)

    return newlist


# 读取词典中的内容
# 加入停用词
stopWord = []
with open('dict/stopwords.txt', 'r', encoding='utf-8') as f:
    for line in f.readlines():
        l = line.strip()
        if l == '\\n':
            l = '\n'
        if l == '\\u3000':
            l = '\u3000'
        stopWord.append(l)

# 读取少见人名
Name = []
with open('dict/Names.txt', 'r', encoding='utf-8') as f:
    for line in f.readlines():
        l = line.strip()
        if l == '\\n':
            l = '\n'
        if l == '\\u3000':
            l = '\u3000'
        Name.append(l)
# 刑事案由
CriminalCase = []
with open('dict/CriminalCase.txt', 'r', encoding='utf-8') as f:
    for line in f.readlines():
        l = line.strip()
        if l == '\\n':
            l = '\n'
        if l == '\\u3000':
            l = '\u3000'
        CriminalCase.append(l)
for i in CriminalCase:
    jieba.add_word(i)

# 民事案由
Civil = []
with open('dict/Civil.txt', 'r', encoding='utf-8') as f:
    for line in f.readlines():
        l = line.strip()
        if l == '\\n':
            l = '\n'
        if l == '\\u3000':
            l = '\u3000'
        Civil.append(l)
for i in Civil:
    jieba.add_word(i)

# 所有民族
Race = []
with open('dict/races.txt', 'r', encoding='utf-8') as f:
    for line in f.readlines():
        l = line.strip()
        if l == '\\n':
            l = '\n'
        if l == '\\u3000':
            l = '\u3000'
        Race.append(l)
for i in Race:
    jieba.add_word(i)


# 删除符号
def delete(wordAndNature):
    temp = wordAndNature
    for i in range(0, len(wordAndNature)):
        temp1 = wordAndNature[i].split('/')
        if temp1[1] == 'w':
            temp[i] = '  '
        else:
            continue
    while '  ' in temp:
        temp.remove('  ')
    wordAndNature = temp
    return wordAndNature


# 人名
def getName(wordAndNature):
    name = []
    for i in range(0, len(wordAndNature) - 2):
        temp1 = wordAndNature[i].split('/')
        temp2 = wordAndNature[i + 1].split('/')
        temp3 = wordAndNature[i + 2].split('/')
        if temp1[1] == 'nz' and temp2[1] == 'nr' and temp3[1] == 'b':
            temp = temp1[0] + ': ' + temp2[0] + '_ ' + temp3[0]
            name.append(temp)
        elif temp1[1] == 'n' and temp2[1] == 'nr' and temp3[1] == 'b':
            temp = temp1[0] + ': ' + temp2[0] + '_ ' + temp3[0]
            name.append(temp)
        elif temp1[1] == 'nr' and (not temp2[1] == 'b' and not temp3[1] == 'b'):
            name.append(temp1[0])
        else:
            continue
    return name


# 刑事
def getCrime(a):
    # jieba分词
    b = jieba.lcut(a)
    x = np.array(b)
    y = np.array(stopWord)
    np.in1d(x, y)
    z = x[~np.in1d(x, y)]
    z = [i for i in z if len(i) > 1]
    inter = list(set(z).intersection(set(CriminalCase)))
    return inter


# 民事
def getCivil(a):
    # jieba分词
    b = jieba.lcut(a)
    x = np.array(b)
    y = np.array(stopWord)
    np.in1d(x, y)
    z = x[~np.in1d(x, y)]
    z = [i for i in z if len(i) > 1]
    inter = list(set(z).intersection(set(Civil)))
    return inter


# 民族
def getRace(a):
    # jieba分词
    b = jieba.lcut(a)
    x = np.array(b)
    y = np.array(stopWord)
    np.in1d(x, y)
    z = x[~np.in1d(x, y)]
    z = [i for i in z if len(i) > 1]
    inter = list(set(z).intersection(set(Race)))
    return inter


# 地点
def getDestination(wordAndNature):
    destination = []
    for i in range(0, len(wordAndNature) - 1):
        temp1 = wordAndNature[i].split('/')
        temp2 = wordAndNature[i + 1].split('/')
        temp = ''
        if temp1[1] == 'ns' and temp2[1] == 'ns':
            temp = temp1[0] + temp2[0]
            destination.append(temp)
        else:
            continue
    if len(destination) == 0:
        destination.append('未提及出生地')
    return destination


# 法院名
def getInstitution(wordAndNature):
    institution = []
    for i in range(0, len(wordAndNature) - 2):
        temp1 = wordAndNature[i].split('/')
        temp2 = wordAndNature[i + 1].split('/')
        temp3 = wordAndNature[i + 2].split('/')
        temp = ''
        if temp1[1] == 'ns' and temp2[1] == 'ns' and temp3[1] == 'nis':
            temp = temp1[0] + temp2[0] + temp3[0]
            institution.append(temp)
        elif temp1[1] != 'ns' and temp2[1] == 'ns' and (temp3[1] == 'nt' or temp3[1] == 'nis'):
            temp = temp2[0] + temp3[0]
            institution.append(temp)
        elif (temp1[1] != 'ns' and temp2[1] != 'ns' and (temp3[1] == 'nt' or temp3[1] == 'nis')) and len(temp3[0]) > 4:
            temp = temp3[0]
            institution.append(temp)
        else:
            continue
        for w in institution:
            if not ('院' in w):
                institution.remove(w)
    return institution


crimeResult = ['有期徒刑', '无期徒刑', '死刑', '缓刑', '管制', '拘役']
circumstances = ['轻微', '较轻', '显著轻微', '恶劣', '严重', '特定情节']


# 犯罪情节
def getCircumstances(wordAndNature):
    crimeCircumstance = []
    for index in range(0, len(wordAndNature)):
        temp = wordAndNature[index].split('/')
        if temp[0] in circumstances:
            crimeCircumstance.append(temp[0])
        else:
            continue
    return crimeCircumstance


# 判处结果
def getCrimeResult(wordAndNature):
    CrimeResult = []
    for index in range(0, len(wordAndNature)):
        temp = wordAndNature[index].split('/')
        if temp[0] in crimeResult:
            CrimeResult.append(temp[0])
        else:
            continue
    return CrimeResult


# 审判性质
court = ['一审', '二审', '终审', '再审', '驳回', '维持', '不予受理']


def courtResult(wordAndNature):
    CourtResult = []
    for index in range(0, len(wordAndNature)):
        temp = wordAndNature[index].split('/')
        if temp[0] in court:
            CourtResult.append(temp[0])
        else:
            continue
    return CourtResult


class DataAnalyse(object):
    def __init__(self):
        self.wordAndNature = ''
        pass

    # 根据文件
    def analyseDirection(self, filePath):
        document = Document(filePath)  # 打开文件
        text = ''
        for paragraph in document.paragraphs:
            text = text + paragraph
        result = self.analyseText(text)
        return result

    # 分析文本
    def analyseText(self, text):
        # HanLp分词
        segment = HanLP.newSegment().enableNameRecognize(True)
        term_list = segment.seg(text)
        wordAndNature = []
        for term in term_list:
            if re.search(r'/', str(term)):
                if (str(term) in wordAndNature) and (not str(term) == '男/b') and (not str(term) == '被告人/n'):
                    continue
                else:
                    wordAndNature.append(str(term))
        wordAndNature = delete(wordAndNature)
        self.wordAndNature = wordAndNature
        # 得到字典结果
        result = self.getResult(text, wordAndNature)
        return result

    def getResult(self, a, wordAndNature):
        # 保存结果
        result = {'Criminals': getName(wordAndNature), 'Ethnicity': getRace(a),
                  'Birthplace': getDestination(wordAndNature), 'Courts': getInstitution(wordAndNature),
                  'Crimes': getCrime(a), 'Results': getCrimeResult(wordAndNature),
                  'Character': courtResult(wordAndNature)}
        return result

    def saveFile(self, result, fileName):
        # 写入json文件，将其命名为不同的文件
        temp = fileName.split('.')
        fileName = temp[0]
        jsonpath = 'saveJSON/' + fileName + '_标注.json'
        with open(jsonpath, 'w') as file:
            json_str = json.dumps(result, indent=0, ensure_ascii=False)
            file.write(json_str)
            file.write('\n')

    # 分词出来的关键词的结果(方便起见每一个函数的变量是相同的)
    def showName(self, a, wordAndNature):
        return getName(wordAndNature)

    def showRace(self, a, wordAndNature):
        return getRace(a)

    def showDestination(self, a, wordAndNature):
        return getDestination(wordAndNature)

    def showInstitution(self, a, wordAndNature):
        return getInstitution(wordAndNature)

    def showCivil(self, a, wordAndNature):
        return getCivil(a)

    def showCrime(self, a, wordAndNature):
        return getCrime(a)

    def showCircumstance(self, a, wordAndNature):
        return getCircumstances(wordAndNature)

    def showCrimeResult(self, a, wordAndNature):
        return getCrimeResult(wordAndNature)

    # 获取名词，动词，形容词
    def getNoun(self, a, wordAndNature):
        Noun = []
        if len(getName(wordAndNature)) > 0:
            for i in getName(wordAndNature):
                Noun.append(i)
        if len(getRace(a)) > 0:
            for i in getRace(a):
                Noun.append(i)
        for i in getCrime(a):
            Noun.append(i)
        for i in getCivil(a):
            Noun.append(i)
        if len(getDestination(wordAndNature)) > 0:
            for i in getDestination(wordAndNature):
                Noun.append(i)
        if len(getInstitution(wordAndNature)) > 0:
            for i in getInstitution(wordAndNature):
                Noun.append(i)
        if len(getCrimeResult(wordAndNature)) > 0:
            for i in getCrimeResult(wordAndNature):
                Noun.append(i)
        if len(courtResult(wordAndNature)) > 0:
            for i in courtResult(wordAndNature):
                Noun.append(i)
        temp = []
        for i in Noun:
            if i == '驳回' or i == '维持' or i == '不予受理':
                continue
            else:
                temp.append(i)
        Noun = temp
        return Noun

    def getVerb(self, a, wordAndNature):
        Verb = []
        for i in range(0, len(wordAndNature)):
            temp = wordAndNature[i].split('/')
            if temp[1] == 'v' or temp[1] == 'vd' or temp[1] == 'vf' or temp[1] == 'vn' or temp[1] == 'vi' or temp[
                1] == 'vl' or temp[0] == '驳回' or temp[0] == '维持' or temp[0] == '不予受理':
                Verb.append(temp[0])
            else:
                continue
        return Verb

    def getAdj(self, a, wordAndNature):
        Adj = []
        if len(getCircumstances(wordAndNature)) > 0:
            for i in getCircumstances(wordAndNature):
                Adj.append(i)
        return Adj



